package iagovsothello.online.server;

public class TimerThread extends Thread {

	private long time;
	private boolean running;
	private boolean restart;
	private ServerWindow window;
	
	public TimerThread(int time, ServerWindow window)
	{
		this.time = time*1000L;
		this.running = false;
		this.restart = false;
		this.window = window;
	}
	
	public TimerThread(int time, boolean restart, ServerWindow window)
	{
		this.time = time*1000L;
		this.running = false;
		this.restart = restart;
		this.window = window;
	}
	
	public synchronized boolean isRunning() 
	{
		return running;
	}

	public synchronized void setRunning(boolean running) 
	{
		this.running = running;
	}
	
	public void run()
	{
		setRunning(true);
		long remainingTime = time;
		long lastTime = System.currentTimeMillis();

		while (isRunning())
		{
			do {
				try {
					sleep(1000);
				} catch (InterruptedException e) { }
				long t = System.currentTimeMillis();
				long diff = t-lastTime;
				remainingTime -= diff;
				lastTime = t;
			} while (remainingTime > 0 && isRunning());

			if (isRunning())
			{
//				window.getTextAreaLog().append("LOL\n");
				if (window.isModified())
				{
					window.saveRecords();
					window.setModified(false);
				}
				if (restart)
					remainingTime = time;
				else
					setRunning(false);
			}
		}
	}
}
